package xiangmu.schoolpaper.interceptor;


import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import xiangmu.schoolpaper.config.JwtProperties;
import xiangmu.schoolpaper.constant.JwtClaimsConstant;
import xiangmu.schoolpaper.context.BaseContext;
import xiangmu.schoolpaper.utils.JwtUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * jwt令牌校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String uri = request.getRequestURI();
        System.out.println("当前请求的uri:"+uri);

        //1、从请求头中获取令牌
        String token = request.getHeader("Authorization");

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            System.out.println("打印秘钥"+jwtProperties.getAdminSecretKey());
            System.out.println("打印过期时间"+jwtProperties.getAdminTtl());

//            解析token
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            System.out.println("打印claims"+claims);

//            将解析出来的信息存入BaseContext类中，方便之后调用
//            ①将userId存入BaseContext中
            Long userId = Long.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前userId：{}",userId);
            BaseContext.set("userId", userId);

//            ②将roleId存入BaseContext中
            Long roleId = Long.valueOf(claims.get(JwtClaimsConstant.ROLE_ID).toString());
            BaseContext.set("roleId", roleId);
            log.info("当前roleId：{}",roleId);

//            ②将roleId存入BaseContext中
            String account = String.valueOf(claims.get(JwtClaimsConstant.USERNAME).toString());
            BaseContext.set("account", account);
            log.info("当前account：{}",account);

//            取值示例
//            Long uid =  (Long) BaseContext.get("userId");
//            Long rid =  (Long) BaseContext.get("roleId");
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            ex.printStackTrace(); // 打印完整异常
            response.setStatus(401);
            return false;
        }
    }


    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) throws Exception {
        // 请求结束后清理 ThreadLocal，防止内存泄漏
        BaseContext.remove();
    }



}
